/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

//BEGIN_INCLUDE(all)
#include "glTestActivity.h"
#include "gl_helpers.h"
#include "ndk_helpers.h"
#include "shaders.h"


#include <jni.h>
#include <errno.h>

#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>

#include <android/sensor.h>
#include <android_native_app_glue.h>



/**
 * Our saved state data.
 */
struct saved_state {
    float angle;
    int32_t x;
    int32_t y;
};

/**
 * Shared state for our app.
 */
struct AppContext {
    struct android_app* app;

    ASensorManager* sensorManager;
    const ASensor* accelerometerSensor;
    ASensorEventQueue* sensorEventQueue;

    int animating;
    EGLDisplay display;
    EGLSurface surface;
    EGLContext context;
    int32_t width;
    int32_t height;
    struct saved_state state;

    GLuint vShader;
    GLuint fShader;
    GLuint shaderProgram;
    GLuint vtxBuffer;
    GLuint eltBuffer;
};

/**
 * Initialize an EGL context for the current display.
 */
static int init_display(AppContext* ctx) {
  // initialize OpenGL ES and EGL

  /*
   * Here specify the attributes of the desired configuration.
   * Below, we select an EGLConfig with at least 8 bits per color
   * component compatible with on-screen windows
   */
  const EGLint attribs[] = {
    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
    //EGL_CONTEXT_CLIENT_VERSION, 2,
    EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
    EGL_BLUE_SIZE, 8,
    EGL_GREEN_SIZE, 8,
    EGL_RED_SIZE, 8,
    EGL_NONE
  };
  EGLint w, h, dummy, format;
  EGLint numConfigs;
  EGLConfig config;
  EGLSurface surface;
  EGLContext context;

  EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

  EGLint major, minor;
  eglInitialize(display, &major, &minor);
  LOGI("eglInitialize returns (%d,%d)", major, minor);


  /* Here, the application chooses the configuration it desires. In this
   * sample, we have a very simplified selection process, where we pick
   * the first EGLConfig that matches our criteria */
  LOGI("eglChooseConfig");
  eglChooseConfig(display, attribs, &config, 1, &numConfigs);
  LOGI("numConfigs=%d", numConfigs);

  /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
   * guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
   * As soon as we picked a EGLConfig, we can safely reconfigure the
   * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */
  LOGI("eglGetConfigAttrib");
  eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);

  LOGI("ANativeWindow_setBuffersGeometry");
  ANativeWindow_setBuffersGeometry(ctx->app->window, 0, 0, format);

  surface = eglCreateWindowSurface(display, config, ctx->app->window, NULL);
  LOGI("eglCreateWindowSurface returns %d", surface);
  const EGLint contextAttribs[] = {
    EGL_CONTEXT_CLIENT_VERSION, 2,
    EGL_NONE
  };
  context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttribs);
  LOGI("eglCreateContext returns %d", context);

  LOGI("eglMakeCurrent");
  if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
    LOGW("Unable to eglMakeCurrent");
    return -1;
  }

  printGLString("Version", GL_VERSION);
  printGLString("Vendor", GL_VENDOR);
  printGLString("Renderer", GL_RENDERER);
  printGLString("Extensions", GL_EXTENSIONS);

  eglQuerySurface(display, surface, EGL_WIDTH, &w);
  eglQuerySurface(display, surface, EGL_HEIGHT, &h);

  ctx->display = display;
  ctx->context = context;
  ctx->surface = surface;
  ctx->width = w;
  ctx->height = h;
  ctx->state.angle = 0;

  // Initialize GL state.
  LOGI("Setup GL state");
//  glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
  glEnable(GL_CULL_FACE);
  glDisable(GL_DEPTH_TEST);

  glViewport(0, 0, w, h);


  // Initialize shaders
  LOGI("Loading shaders...");
  ctx->vShader = LoadShader(GL_VERTEX_SHADER, shaders::vshBasic);
  ctx->fShader = LoadShader(GL_FRAGMENT_SHADER, shaders::fshBasic);
  LOGI("...done\n");

  ctx->shaderProgram = glCreateProgram();
  glAttachShader(ctx->shaderProgram, ctx->vShader);
  glAttachShader(ctx->shaderProgram, ctx->fShader);

  GLuint attrIndex = 0;
  
  glVertexAttrib4f(attrIndex, 1.0f, 1.0f, 1.0f, 1.0f);
  glBindAttribLocation(ctx->shaderProgram, attrIndex, "a_color");
  ++attrIndex;

  static GLfloat verts[] = {
    0.0f,  .5f, 0.0f,
    -.5f, -.5f, 0.0f,
     .5f, -.5f, 0.0f
  };
  glVertexAttribPointer(
    attrIndex,  // attribute index
    3,          // number of elements in attribute (in this case 3, since
                // we're specifying an array of 3-element vectors)
    GL_FLOAT,   // type of each element
    GL_FALSE,   // normalize == false (apparently this is useful with fixed
                // point values?)
    0,          // stride between elements. Note that this is the stride
                // from the end of one element to the beginning of the next,
                // unlike D3D where it's beginning to beginning.
    verts       // pointer to data. Note there's no size, which is why using
                // this API is probably a bad idea.
  );
  glEnableVertexAttribArray(attrIndex);
  glBindAttribLocation(ctx->shaderProgram, attrIndex, "a_pos");
  ++attrIndex;

  glLinkProgram(ctx->shaderProgram);
  CheckShaderStatus(ctx->shaderProgram, GL_LINK_STATUS);
  return 0;
}

/**
 * Just the current frame in the display.
 */
static void draw_frame(AppContext* ctx) {
  if (ctx->display == NULL) {
    // No display.
    LOGW("No display!!");
    return;
  }

  // Just fill the screen with a color.
  glClearColor(0.6f, 0.3f, 0.3f, 1);
  glClear(GL_COLOR_BUFFER_BIT);


  glUseProgram(ctx->shaderProgram);
  glDrawArrays(GL_TRIANGLES, 0, 3);


  eglSwapBuffers(ctx->display, ctx->surface);
}

/**
 * Tear down the EGL context currently associated with the display.
 */
static void term_display(AppContext* ctx) {
  glUseProgram(0);
  glDeleteProgram(ctx->shaderProgram);
  glDeleteShader(ctx->vShader);
  glDeleteShader(ctx->fShader);

  if (ctx->display != EGL_NO_DISPLAY) {
    eglMakeCurrent(ctx->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
    if (ctx->context != EGL_NO_CONTEXT) {
        eglDestroyContext(ctx->display, ctx->context);
    }
    if (ctx->surface != EGL_NO_SURFACE) {
        eglDestroySurface(ctx->display, ctx->surface);
    }
    eglTerminate(ctx->display);
  }
  ctx->animating = 0;
  ctx->display = EGL_NO_DISPLAY;
  ctx->context = EGL_NO_CONTEXT;
  ctx->surface = EGL_NO_SURFACE;
}

/**
 * Process the next input event.
 */
static int32_t handle_input(struct android_app* app, AInputEvent* event) {
    AppContext* ctx = (AppContext*)app->userData;
    if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) {
        ctx->animating = 1;
        ctx->state.x = AMotionEvent_getX(event, 0);
        ctx->state.y = AMotionEvent_getY(event, 0);
        return 1;
    }
    return 0;
}

/**
 * Process the next main command.
 */
static void handle_cmd(struct android_app* app, int32_t cmd) {
    AppContext* ctx = (AppContext*)app->userData;
    switch (cmd) {
        case APP_CMD_SAVE_STATE:
            // The system has asked us to save our current state.  Do so.
            ctx->app->savedState = malloc(sizeof(struct saved_state));
            *((struct saved_state*)ctx->app->savedState) = ctx->state;
            ctx->app->savedStateSize = sizeof(struct saved_state);
            break;
        case APP_CMD_INIT_WINDOW:
            // The window is being shown, get it ready.
            if (ctx->app->window != NULL) {
                init_display(ctx);
                draw_frame(ctx);
            }
            break;
        case APP_CMD_TERM_WINDOW:
            // The window is being hidden or closed, clean it up.
            term_display(ctx);
            break;
        case APP_CMD_GAINED_FOCUS:
            // When our app gains focus, we start monitoring the accelerometer.
            if (ctx->accelerometerSensor != NULL) {
                ASensorEventQueue_enableSensor(ctx->sensorEventQueue,
                        ctx->accelerometerSensor);
                // We'd like to get 60 events per second (in us).
                ASensorEventQueue_setEventRate(ctx->sensorEventQueue,
                        ctx->accelerometerSensor, (1000L/60)*1000);
            }
            break;
        case APP_CMD_LOST_FOCUS:
            // When our app loses focus, we stop monitoring the accelerometer.
            // This is to avoid consuming battery while not being used.
            if (ctx->accelerometerSensor != NULL) {
                ASensorEventQueue_disableSensor(ctx->sensorEventQueue,
                        ctx->accelerometerSensor);
            }
            // Also stop animating.
            ctx->animating = 0;
            draw_frame(ctx);
            break;
    }
}

/**
 * This is the main entry point of a native application that is using
 * android_native_app_glue.  It runs in its own thread, with its own
 * event loop for receiving input events and doing other things.
 */
void android_main(struct android_app* state) {
    AppContext ctx;

    // Make sure glue isn't stripped.
    app_dummy();

    

    memset(&ctx, 0, sizeof(ctx));
    state->userData = &ctx;
    state->onAppCmd = handle_cmd;
    state->onInputEvent = handle_input;
    ctx.app = state;

    // Prepare to monitor accelerometer
    ctx.sensorManager = ASensorManager_getInstance();
    ctx.accelerometerSensor = ASensorManager_getDefaultSensor(ctx.sensorManager,
            ASENSOR_TYPE_ACCELEROMETER);
    ctx.sensorEventQueue = ASensorManager_createEventQueue(ctx.sensorManager,
            state->looper, LOOPER_ID_USER, NULL, NULL);

    if (state->savedState != NULL) {
        // We are starting with a previous saved state; restore from it.
        ctx.state = *(struct saved_state*)state->savedState;
    }

    // loop waiting for stuff to do.

    while (1) {
        // Read all pending events.
        int ident;
        int events;
        struct android_poll_source* source;

        // If not animating, we will block forever waiting for events.
        // If animating, we loop until all events are read, then continue
        // to draw the next frame of animation.
        while ((ident=ALooper_pollAll(ctx.animating ? 0 : -1, NULL, &events,
                (void**)&source)) >= 0) {

            // Process this event.
            if (source != NULL) {
                source->process(state, source);
            }

            // If a sensor has data, process it now.
            if (ident == LOOPER_ID_USER) {
                if (ctx.accelerometerSensor != NULL) {
                    ASensorEvent event;
                    while (ASensorEventQueue_getEvents(ctx.sensorEventQueue,
                            &event, 1) > 0) {
/*
                        LOGI("accelerometer: x=%f y=%f z=%f",
                                event.acceleration.x, event.acceleration.y,
                                event.acceleration.z);
*/
                    }
                }
            }

            // Check if we are exiting.
            if (state->destroyRequested != 0) {
                term_display(&ctx);
                return;
            }
        }

        if (ctx.animating) {
            // Done with events; draw next animation frame.
            ctx.state.angle += .01f;
            if (ctx.state.angle > 1) {
                ctx.state.angle = 0;
            }

            // Drawing is throttled to the screen update rate, so there
            // is no need to do timing here.
            draw_frame(&ctx);
        }
    }
}
//END_INCLUDE(all)
